import * as vscode from 'vscode';
import { TodoProvider } from './providers/todo-provider';
import { StatsProvider } from './providers/stats-provider';
import { CommandService } from './services/command.service';

export async function activate(context: vscode.ExtensionContext) {
  // 初始化服务和提供者
  const todoProvider = new TodoProvider(context);
  const statsProvider = new StatsProvider(todoProvider);
  const commandService = new CommandService(
    context,
    todoProvider,
    statsProvider
  );

  // 注册命令
  commandService.registerCommands();

  // 创建树视图
  const todoTreeView = vscode.window.createTreeView('easytodo-list', {
    treeDataProvider: todoProvider,
    dragAndDropController: createDragAndDropController(
      todoProvider,
      statsProvider
    ),
  });

  const statsTreeView = vscode.window.createTreeView('easytodo-stats', {
    treeDataProvider: statsProvider,
  });
}

// 创建拖放控制器
function createDragAndDropController(
  todoProvider: TodoProvider,
  statsProvider: StatsProvider
): vscode.TreeDragAndDropController<any> {
  return <vscode.TreeDragAndDropController<any>>{
    dropMimeTypes: ['application/vnd.code.tree.easytodo'],
    dragMimeTypes: ['application/vnd.code.tree.easytodo'],
    canDrag: (items: vscode.TreeItem[]): boolean => {
      return items.length === 1 && (items[0] as any)?.task !== undefined;
    },
    handleDrag: (
      source: vscode.TreeItem[],
      dataTransfer: vscode.DataTransfer
    ): void | Thenable<void> => {
      const item = source[0] as any;
      if (item?.task) {
        const transferData = {
          type: item.type,
          task: item.task,
          groupId: item.task.groupId,
        };
        dataTransfer.set(
          'application/vnd.code.tree.easytodo',
          new vscode.DataTransferItem(JSON.stringify(transferData))
        );
      }
    },
    handleDrop: async (target: any, dataTransfer: vscode.DataTransfer) => {
      const transferItem = await dataTransfer.get(
        'application/vnd.code.tree.easytodo'
      );
      if (!transferItem) return;

      const sourceItem = JSON.parse(transferItem.value);
      if (!sourceItem) return;

      // 处理任务拖拽到分组
      if (sourceItem.type === 'task' && target?.type === 'group') {
        await todoProvider.moveTask(sourceItem.task.id, target.task.id);
        statsProvider.refresh();
        return;
      }

      // 处理任务排序
      if (sourceItem.type === 'task' && (!target || target.type === 'task')) {
        const targetTask = target ? target.task : null;
        const targetGroupId = target?.task?.groupId || null;

        // 如果目标任务在不同分组，先移动到目标分组
        if (sourceItem.groupId !== targetGroupId) {
          await todoProvider.moveTask(sourceItem.task.id, targetGroupId);
        }

        await todoProvider.reorderTask(sourceItem.task.id, targetTask?.id);
        statsProvider.refresh();
        return;
      }

      // 处理分组排序
      if (sourceItem.type === 'group' && (!target || target.type === 'group')) {
        const targetGroup = target ? target.task : null;
        await todoProvider.reorderGroup(sourceItem.task.id, targetGroup?.id);
        statsProvider.refresh();
        return;
      }
    },
  };
}
